package org.anderground.editor.gui.properties.line;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JColorChooser;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import org.anderground.core.model.Line;
import org.anderground.editor.edits.EditsManager;
import org.anderground.editor.edits.SetLineColorAction;
import org.anderground.editor.gui.properties.AbstractPropertiesPanel;
import org.anderground.editor.gui.properties.ColorPanel;

public class LineColorProperty implements AbstractPropertiesPanel.Property {

	@Override
	public TableCellEditor getCellEditor() {
		@SuppressWarnings("serial")
		class T extends AbstractCellEditor implements TableCellEditor {

			@Override
			public Component getTableCellEditorComponent(JTable table,
					Object value, boolean isSelected, int row, int column) {
				// FIXME
				final Line line = (Line) value;
				class T2 extends ColorPanel {
					public T2() {
						super(line.getColor());
						final JColorChooser colorChooser = new JColorChooser(
								new Color(line.getColor()));
						ActionListener onOk = new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								EditsManager.getInstance().performAction(
										new SetLineColorAction(line,
												colorChooser.getColor()
														.getRGB()));
								T.this.stopCellEditing();

							}

						};
						ActionListener onCancel = new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								T.this.stopCellEditing();
							}

						};

						JColorChooser.createDialog(T2.this,
								"Choose line color", true, colorChooser, onOk,
								onCancel).setVisible(true);
					}
				}
				return new T2();
			}

			@Override
			public Object getCellEditorValue() {
				return null;
			}
		}
		return new T();
	}

	@Override
	public TableCellRenderer getCellRender() {
		return new TableCellRenderer() {

			@Override
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column) {
				// FIXME
				Line line = (Line) value;
				return new ColorPanel(line.getColor());
			}

		};

	}

	@Override
	public String getPropertyName() {
		return "Color";
	}

	@Override
	public boolean isEditable() {
		return true;
	}

}
